package beans.lifecycle;

import cn.stimd.spring.beans.BeansException;
import cn.stimd.spring.beans.factory.config.InstantiationAwareBeanPostProcessor;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class SimpleProxyPostProcessor implements InstantiationAwareBeanPostProcessor {
    private Set<String> cache = new HashSet<>();

    @Override
    public Object getEarlyBeanReference(Object bean, String beanName) {
        System.out.println("提前暴露代理对象[" + beanName + "]");
        this.cache.add(beanName);
        return createProxy(bean);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (!this.cache.contains(beanName)) {
            System.out.println("初始化后创建代理对象[" + beanName + "]");
            //返回代理对象，而非原始对象
            return createProxy(bean);
        }
        return bean;
    }

    private Object createProxy(Object bean) {
        if (bean instanceof ITarget) {
            return new SimpleProxy(bean).getProxy();
        }
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }

    @Override
    public void postProcessPropertyValues(Object bean, String beanName) {

    }
}
